function CODE = huffman(f)
error(nargchk(1,1,nargin));
if (ndims(f) ~= 2) || (min(size(f))>1) || ~isreal(f) || ~isnumeric(f)
error('P must be a real numeric vector.');
end
 
global CODE                       %global variable 
CODE = cell(length(f),1);            
if length(f) > 1                     
f = f/sum(f);                     % Normalize the input probabilities
d = reduction(f);                 % Do Huffman source symbol reductions
codegeneration(d, []);            % Recursively generate the code
else
CODE = {'0'};                     % Else, trivial one symbol case
end
%������������������������.%
function m = reduction(p)
m =  cell(length(p),1);
for i = 1:length(p)
m{i} = i;
end
while numel(m) > 2
[p,i] = sort(p);             % Sort the symbol probabilities
display(p);
p(2) = p(1) + p(2);          % Merge the 2 lowest probabilities
p(1) = [];
display(p);
m = m(i);                    
m{2} = {m{1},m{2}};          % and merge & prune its nodes
m(1) = [];                                   
end
%������������������������.%
function codegeneration(sc, codeword)
global CODE
if isa(sc,'cell')                                          
codegeneration(sc{1},[codeword 1]);         % add 1 if the 1st element
codegeneration(sc{2}, [codeword 0]);        % add 0 if the 2nd element
else                                                          
CODE{sc} = char('0' + codeword);     % create a char code string
end
